<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>
  * {
    margin: 0;
    padding: 0;
  }

  .box {
    width: 800px;
    margin: 0 auto;
  }

  .imgBox {
    width: 100%;
    height: 300px;
    background-color: #ccc;
    margin-top: 10px;
  }

  img {
    width: 100%;
    height: 100%;
  }
</style>

<body>
  <div class="box">

  </div>
  <script src="./js/jquery.js"></script>
  <script>
    let $box = $('.box'),
      $imgBox = null
    let str = ``
    //创建长度为10，内容为null的数组
    new Array(10).fill(null).forEach(item => {
      // 循环遍历每一个数组，将模板字符串填充到数组中
      str += `<div class="imgBox">
      <img src="" alt=""
        data-img="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg9.51tietu.net%2Fpic%2F2019-091023%2F5bahqp4g4qh5bahqp4g4qh.jpg&refer=http%3A%2F%2Fimg9.51tietu.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1638581059&t=98f97e8f5573dac578029b849431123b">
    </div>`
    })
    $box.html(str)
    $imgBox = $box.children('.imgBox')
    let $window = $(window)
    $window.on('load scroll', function () {
      let $scrollTop = $window.outerHeight() + $window.scrollTop()    //页面滚动的高度
      // console.log($scrollTop);
      // 循环遍历每一张图片区域，获取当前图片距离页面顶部的距离
      $imgBox.each((index, item) => {
        let $item = $(item),
          $itemImgTop = $item.outerHeight() + $item.offset().top
        isLoad = $item.attr('isLoad')
        // 如果图片距离页面顶部的高度小于等于页面滚动的高度，并且isLoad不等于'true'，那么图片就加载
        if ($itemImgTop <= $scrollTop && isLoad !== "true") {
          $item.attr('isLoad', true)
          // 获取每一个img标签
          let $img = $item.children('img')
          // 获取img标签的自定义属性的值，赋值给src属性
          $img.attr("src", $img.attr("data-img"))
          $img.on('load', function () {
            // 设置为淡入效果
            $img.fadeIn()
          })
        }
      })
    })


  </script>
</body>

</html>